/**
 * 数据库模块
 */
//var db = require("./config.json");
var db = {
	"host": "localhost",
	"port": "3306",
	"user": "root",
	"password": "xzw_jinstudio2012",
	"database": "newxshdb",
	"charset": "UTF8",
	"maxConnLimit": 200
}
var options = {
	'host'               : db.host,
	'port'               : db.port,
	'user'               : db.user,
	'password'           : db.password,
	'database'           : db.database,
	'charset'            : db.charset,
	'connectionLimit'    : db.maxConnLimit,
	'supportBigNumbers'  : true,
	'bigNumberStrings'   : true,
	'multipleStatements' : true

};

var mysql = require('mysql');
var pool = mysql.createPool(options);

/**
 * 释放数据库连接
 */
module.exports.release = function(connection) {
	connection.end(function(error) {
		console.log('Connection closed');
	});
};

/**
 * 执行查询
 */
module.exports.execQuery = function(options) {
	pool.getConnection(function(error, connection) {
		if (error) {
			console.log('DB-获取数据库连接异常！');
			throw error;
		}
		console.log('===》获取连接成功');
		console.log('connectionId ===>' + connection.threadId);
		/*
		 * connection.query('USE ' + config.db, function(error, results) { if(error) { console.log('DB-选择数据库异常！'); connection.end(); throw error; } });
		 */

		// 查询参数
		var sql = options['sql'];
		var args = options['args'];
		var handler = options['handler'];

		// 执行查询
		if (!args) {
			var query = connection.query(sql, function(error, results) {
				if (error) {
					console.log('DB-执行查询语句异常！');
					throw error;
				}

				// 处理结果
				handler(results);
			});

			console.log(query.sql);
		} else {
			var query = connection.query(sql, args, function(error, results) {
				// 返回连接池
				connection.release(function(error) {
					if (error) {
						console.log('DB-关闭数据库连接异常！');
						throw error;
					}
					console.log('====>成功返回连接池');
				});
				if (error) {
					console.log('DB-执行查询语句异常！');
					throw error;
				}
				
				// 处理结果
				handler(results);
				console.log('====> after handler')
			});

			console.log(query.sql);
		}

		connection.on('error',function(err){
			console.log(err);
		});
	});
};